
//新版基础函数
var f = {
    init:function() {
        log("程序初始化成功")
    },
    //post
    post : function(url,data){
        var res = http.post(url, data);
        var data = res.body.string();
        if(data){
            // log(data);
            return data;
        }
    },
    //get
    get : function(url){
        var res = http.get(url);
        var data = res.body.string();
        if(data){
            return data;
        }
    },
    //读取本地数据
    getLocal:function ( name, key) {
        const storage = storages.create(name);  //创建storage对象
        if (storage.contains(key)) {
            return storage.get(key);
        };
        //默认返回undefined
    },
    //基础函数
    active:function(pkg,n){
        if(!n){n=5}
        if(  currentPackage() == pkg ){
            log("应用在前端");
            return true;
        }else{
            log("启动一次应用");
            app.launch(pkg);
            sleep(1000)
            f.ms({"textMatches":"允许|始终允许"},true)
            sleep(1000*n)
        }
    },
    //准备点击
    click:function (x,y,sleeptime,name){
        if ( ! sleeptime ){sleeptime = 1}
        if ( name ){
            log('准备点击->'+name,"x:",x,"y:",y);
        }else{
            log('准备点击坐标->', "x:",x,"y:",y);
        }
        if( x > 0  && y > 0  ){
            threads.start(function(){
                //在新线程执行的代码
                click(x,y);
            });
            // click(x,y);
            sleep(sleeptime*1000);
            return true
        }else{
            log('坐标错误');
        }
    },
    //点击obj
    clickObj:function (obj,sleeptime,name){
        if ( ! sleeptime ){ sleeptime == 1 } 
        log(  name ? ("准备点击对象->" + name) : "点击未命名对象" )
        x = obj.bounds().centerX()
        y = obj.bounds().centerY()
        return f.click(x,y,sleeptime,name)
    },
    //穿透点击
    clickTrue:function(obj,sleeptime,name,lun){
        sleeptime ? sleeptime : 1
        let result = false;
        lun ? lun : 3
        for (let i=0;i<lun;i++){
            if (  obj && obj.clickable() ){
                obj.click();
                log(  name ? ("准备穿透点击对象->" + name) : "准备穿透点击未命名对象" )
                result = true
                break
            }
            obj = obj.parent()
        }
        if ( result ) { sleep(sleeptime * 1000) }
        return result
    },
    //正则点击
    ms:function (obj,clicks,sleeptimes,name,findtime,lun){
        if (!sleeptimes) { sleeptimes = 1}
        if (!findtime) { findtime = 200}
        if (!lun) { lun = 3}

        var txt = '';
        for(let key in obj){
            if ( key.search("Matches") > 0 ){
                eval("var matches = /" + obj[key] + "/")
                txt = txt + key+'('+matches+').'
            }else if( key ==  'boundsInside' ){
                txt = txt + key+'('+obj[key]+').'
            }else{
                txt = txt + key+'("'+obj[key]+'").'
            }
        }
        var txt = "let objs = "+txt+"findOne("+findtime+");"
        log(txt)
        eval(txt)
        if ( objs ) {
            log( '找到==>' + objs.text() || objs.desc() || objs.id() || objs.className() )
            if ( clicks ){
                name = obj['textMatches'] || obj['descMatches'] || obj['idMatches'] || obj['text'] || obj['desc'] || obj['id']
                if (lun < 1 || !f.clickTrue( objs,sleeptimes,name,lun )){
                    log('准备坐标点击')
                    return f.clickObj( objs,sleeptimes,name );
                }
            }
            return true;
        }
    },
    rd:function (min,max){
        if (min<=max){
            return random(min,max)
        }else{
            return random(max,min)
        }
    },
    moveTo:function (percentX, percentY, percentX1, percentY1, times) {
        // 获取设备的宽度和高度
        const width = device.width;
        const height = device.height;

        // 将百分比转换为实际坐标
        const x = Math.round(width * percentX);
        const y = Math.round(height * percentY);
        const x1 = Math.round(width * percentX1);
        const y1 = Math.round(height * percentY1);

        // 执行滑动操作
        swipe(x, y, x1, y1, times);
        sleep(1000);
    }
}
f.init()

var width = 720;
var height = 1440;
var width = device.width;
var height = device.height;
var phoneMode = device.brand;

log([currentPackage(),currentActivity(),width,height]);

// 新增一个 post 方法，请求头为 json 格式，只需要传入 data 参数
f.postJson = function(data) {
    let url = 'https://api.wenfree.cn/?s=App.Autojs_Hema.Hema'
    var headers = {
        "Content-Type": "application/json"
    };
    log(url,JSON.stringify(data))
    var res = http.postJson(url, data, headers);
    var data = res.body.string();
    if(data){
        log(data);
        return data;
    }
};


function getTitleConent(){
    if ( currentActivity() == "com.wudaokou.hippo.search.SearchActivity" ){
        log("进入搜索界面")
        //没有分类就返回
        if ( !appInfo.category){
            return true;
        }

        try {
            appInfo['search_key'] = id("tv_search_editable_keyword").findOne(200).text()

            let allprice = textMatches("¥.*").find();
            // log(allprice[0].text())
            for (let i=0;i<allprice.length;i++){
                let price = allprice[i].text()
                
                // 假设 allprice[i] 是当前元素，获取其兄弟节点的 text 内容作为 title
                function getTitle(objects){
                    let siblings = objects.parent().children();
                    let title = '';
                    for (let j = 0; j < siblings.length; j++) {
                        let siblingText = siblings[j].text();
                        if (siblingText.length > 6) {
                            title += siblingText + ' ';
                            return title.trim();
                        }
                    }
                }
                let title = getTitle(allprice[i]);
                log(title, price)
        
                var postData = {
                    "city": "北京",
                    "local": appInfo.local,
                    "category": appInfo.category,
                    "category2": appInfo.category2,
                    "search_key": appInfo['search_key'],
                    "title": title,
                };
                
                if (price.includes('/')) {
                    postData['price'] = price;
                } else {
                    postData['vip'] = price;
                }
                f.postJson(postData)
            }
        }catch (error) {
            log('获取标题内容失败', error);
        }
        
        if (f.ms({"textMatches":"还有.*个已售完商品"}, true ) ){
            //这里要把这个点开
        }else
        if( f.ms({"textMatches":"我可是有底线的哦||正在加载更多||RECOMMEND"}) ){
            return true
        }
    
        f.moveTo(0.5,0.8,0.5,0.5,1000)
    }
}





// if (getTitleConent()) {
//     back();
// }

var appInfo = {
    category: '',
    category2: '',
    search_key: '',
    title: '',
    price: '',
}
var storage = storages.create("hema");
var look = []
look = storage.get("look") || [];
// storage.remove("look");
log(look)

function todoMain(){
    if ( f.ms({text:"分类"}) ){
        log("进入首页")
        let current_category = descMatches("已选中.*").findOne(200);
        if( current_category ){
            appInfo['category'] = current_category.desc().replace("已选中，","")
            log("已选中>>", appInfo['category'] )
            if (appInfo['category'] == '为你推荐' ){
                f.moveTo(0.5, 0.8, 0.5, 0.3, 1000)
                return
            }
        }
    }
    
    let allButton = className("android.widget.Button").depth('20').find();
    if(allButton){
        let moveKey = true
        for (let i=0;i<allButton.length;i++){
            let button = allButton[i];
            log(button.desc())
            if ( !look.includes(button.desc()) ){
                // 检查按钮中心点是否超出屏幕范围
                const bounds = button.bounds();
                const centerX = bounds.centerX();
                const centerY = bounds.centerY();
                const screenWidth = device.width;
                const screenHeight = device.height;

                if (centerX < 0 || centerX > screenWidth || centerY < 0 || centerY > screenHeight-300) {
                    // 按钮中心点超出屏幕范围，向上滑动一点儿
                    f.moveTo(0.5, 0.8, 0.5, 0.3, 1000);
                    break;
                }else{
                    appInfo['category2'] = button.desc()
                    f.clickObj(button, 5, button.desc())
                    look.push(button.desc())
                    storage.put("look", look);
                    moveKey = false
                    break;
                }
            }
        }
        if(moveKey){
            f.moveTo(0.5,0.8,0.5,0.5,1000)
        }
    }else{
        log("没有更多分类了")
        exit()
    }
}


f.active("com.wudaokou.hippo", 10)

let titleRecord = ""
let titleCount = 0
while (1){

    if ( !appInfo.local ){
        f.ms({ "text": "首页" }, true)
    }

    if (f.ms({ "id": 'home_page_titlebar_location_text' })) {
        log("进入首页")
        let local = id("home_page_titlebar_location_text").findOne(200);
        if (local) {
            appInfo['local'] = local.text()
            log("所在地", appInfo['local'])
        }

        f.ms({ "text": "分类" }, true)
    }

    todoMain()
    if( getTitleConent() ){
        back()
        sleep(5000)
    }
    // if( titleRecord == appInfo['category2'] ){
    //     titleCount++
    //     log("当前分类",titleRecord,"次数",titleCount)
    //     if ( titleCount > 9 ){
    //        back()
    //        sleep(5000)
    //     }
    // }else{
    //     titleRecord = appInfo['category2']
    //     titleCount = 0
    // }
}







